# from datetime import datetime # 原来用的注释掉
from django.utils import timezone as datetime # 不想大面积修改就这么做
from django.http import JsonResponse
from myadmin.models import Cluster, User, Pod
from dao.install_cluster import install_cluster
from dao.delete_cluster import delete_cluster
from dao.get_cluster import get_cluster
from dao.get_pods import get_pods
from dao.oneClick_deploy import oneClick_deploy


def index(request):
    '''浏览集群信息'''
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    qs = Cluster.objects.filter(status__gt=0)  # 状态大于0
    list = []
    ok = 0
    not_ok = 0

    for cob in qs:
        if cob.status == 1:
            ok += 1
        else:
            not_ok += 1

        dir = cob.toDict()
        uob = User.objects.get(id=cob.user_id)
        dir['username'] = uob.username  # 多表查询，添加集群所属用户
        dir['nickname'] = uob.nickname  # 多表查询，添加集群所属用户
        pod_list = []
        try:
            pod_qs = Pod.objects.filter(cluster_name=cob.name)
            for pod in pod_qs:
                pod_list.append(pod.toDict())
        except Exception as err:
            print(err)
        dir['pod_list'] = pod_list
        list.append(dir)

    return JsonResponse({'state': 1, 'msg': list, 'ok': ok, 'notOk': not_ok})


def insert(request):
    '''执行添加'''
    types = int(request.POST.get('types'))
    rs = install_cluster(types)  # 如果在本机测试，则注释掉此行
    if rs[1] != 0:
        ob = Cluster.objects.get(id=rs[1])
        ob.name = rs[0]
        ob.status = 1
        ob.user_id = int(request.POST.get('user_id'))  # 前端下拉框传入
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'state': 1, 'msg': '添加成功'}
    else:
        try:
            ob = Cluster()
            ob.name = rs[0]
            ob.types = types
            ob.status = 1
            ob.user_id = request.POST.get('user_id')  # 前端下拉框传入
            ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.save()
            context = {'state': 1, 'msg': '添加成功'}
        except Exception as err:
            print(err)
            context = {'state': 0, "msg": "添加失败"}
    return JsonResponse(context)


def delete(request, uid):
    '''删除信息'''
    try:
        ob = Cluster.objects.get(id=uid)
        name = ob.name
        types = ob.types
        delete_cluster(name, types)
        ob.status = 0
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'state': 1, "msg": "删除成功！"}
    except Exception as err:
        print(err)
        context = {'state': 0, "msg": "删除失败"}

    return JsonResponse(context)
    # return render(request, "myadmin/info.html", context)


def update(request, uid):
    '''执行编辑'''
    try:
        ob = Cluster.objects.get(id=uid)
        # ob.name = request.POST.get('name')
        ob.user_id = request.POST.get('user_id')
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'state': 1, "msg": "修改成功！"}
    except Exception as err:
        print(err)
        context = {'state': 0, "msg": "修改失败"}
    return JsonResponse(context)


def refresh(request):
    get_cluster()  # 刷新cluster
    get_pods()  # 刷新pod
    '''浏览集群信息'''
    # 返回一个 QuerySet 对象 ，包含所有的表记录
    qs = Cluster.objects.filter(status__gt=0)  # 状态大于0
    list = []
    ok = 0
    not_ok = 0

    for cob in qs:
        if cob.status == 1:
            ok += 1
        else:
            not_ok += 1

        dir = cob.toDict()
        uob = User.objects.get(id=cob.user_id)
        dir['username'] = uob.username  # 多表查询，添加集群所属用户
        dir['nickname'] = uob.nickname  # 多表查询，添加集群所属用户
        pod_list = []
        try:
            pod_qs = Pod.objects.filter(cluster_name=cob.name)
            for pod in pod_qs:
                pod_list.append(pod.toDict())
        except Exception as err:
            print(err)
        dir['pod_list'] = pod_list
        list.append(dir)

    return JsonResponse({'state': 1, 'msg': list, 'ok': ok, 'notOk': not_ok})


def deploy(request):
    num = int(request.POST.get('num'))
    types = int(request.POST.get('types'))
    user_id = int(request.POST.get('user_id'))
    start = oneClick_deploy(num, types)
    name = ['spark', 'hadoop']
    context = {'state': 1, "msg": "一键部署成功"}
    for i in range(start, start + num):
        try:
            ob = Cluster()
            ob.name = name[types-1] + str(i)
            ob.types = types
            ob.status = 1
            ob.user_id = user_id
            ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.save()
        except Exception as err:
            print(err)
            context = {'state': 0, "msg": "添加失败"}
    return JsonResponse(context)
